package main

import (
	"encoding/base64"
	"encoding/json"
	"io"
	"log"
	"net/http"
	"net/netip"
	"os"
)

func init() {
	file, err := os.OpenFile("./ping.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0660)
	if err != nil {
		panic(err)
	}
	log.SetOutput(file)
}
func ping(w http.ResponseWriter, r *http.Request) {
	var data = make(map[string]any)
	xRealIP := r.Header.Get("X-Real-IP")
	if xRealIP != "" {
		data["ip"] = xRealIP
	} else {
		addrPort, _ := netip.ParseAddrPort(r.RemoteAddr)
		data["ip"] = addrPort.Addr().String()
	}
	body, _ := io.ReadAll(r.Body)
	defer r.Body.Close()
	data["body"] = string(body)
	data["body_base64"] = base64.StdEncoding.EncodeToString(body)
	_ = r.ParseForm()
	data["X-Real-IP"] = r.Header.Get("X-Real-IP")
	data["X-Forwarded-For"] = r.Header.Get("X-Forwarded-For")
	data["uri"] = r.RequestURI
	data["host"] = r.Host
	data["method"] = r.Method
	data["header"] = r.Header
	data["form"] = r.Form
	data["post_form"] = r.PostForm
	data["multipart_form"] = r.MultipartForm
	marshal, _ := json.Marshal(&data)
	w.Header().Set("Content-Type", "application/json")
	_, _ = w.Write(marshal)
	log.Println(string(marshal))
}
